<template>
  <div class="product-add-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="120px"
      size="large"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <el-icon><InfoFilled /></el-icon>
            <span>基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入商品名称"
                maxlength="200"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <el-select
                v-model="form.categoryId"
                placeholder="请选择商品分类"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="category in categoryOptions"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input
                v-model="form.brand"
                placeholder="请输入品牌"
                maxlength="100"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input
                v-model="form.model"
                placeholder="请输入型号"
                maxlength="100"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-card>
      
      <!-- 价格库存 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <el-icon><Money /></el-icon>
            <span>价格库存</span>
          </div>
        </template>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="销售价格" prop="price">
              <el-input-number
                v-model="form.price"
                :precision="2"
                :min="0"
                :max="999999.99"
                placeholder="请输入销售价格"
                style="width: 100%"
              />
              <span class="form-tip">元</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本价格" prop="costPrice">
              <el-input-number
                v-model="form.costPrice"
                :precision="2"
                :min="0"
                :max="999999.99"
                placeholder="请输入成本价格"
                style="width: 100%"
              />
              <span class="form-tip">元</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stockQuantity">
              <el-input-number
                v-model="form.stockQuantity"
                :min="0"
                :max="999999"
                placeholder="请输入库存数量"
                style="width: 100%"
              />
              <span class="form-tip">件</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="低库存阈值" prop="lowStockThreshold">
              <el-input-number
                v-model="form.lowStockThreshold"
                :min="0"
                :max="999999"
                placeholder="请输入低库存阈值"
                style="width: 100%"
              />
              <span class="form-tip">件</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 物理属性 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <el-icon><Box /></el-icon>
            <span>物理属性</span>
          </div>
        </template>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="重量" prop="weight">
              <el-input-number
                v-model="form.weight"
                :precision="3"
                :min="0"
                :max="999.999"
                placeholder="请输入重量"
                style="width: 100%"
              />
              <span class="form-tip">kg</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积" prop="volume">
              <el-input-number
                v-model="form.volume"
                :precision="3"
                :min="0"
                :max="999.999"
                placeholder="请输入体积"
                style="width: 100%"
              />
              <span class="form-tip">m³</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 商品图片 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <el-icon><Picture /></el-icon>
            <span>商品图片</span>
          </div>
        </template>
        
        <ImageUpload
          v-model="form.images"
          :max-count="10"
          :max-size="5"
          accept="image/*"
        />
      </el-card>
      
      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button size="large" @click="handleCancel">
          取消
        </el-button>
        <el-button
          type="primary"
          size="large"
          :loading="loading"
          @click="handleSubmit"
        >
          保存商品
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { InfoFilled, Money, Box, Picture } from '@element-plus/icons-vue'
import ImageUpload from './ImageUpload.vue'
import type { ProductAddRequest, ProductImageRequest } from '@/api/product'

// 定义事件
const emit = defineEmits<{
  submit: [data: ProductAddRequest]
  cancel: []
}>()

// 定义属性
const props = defineProps<{
  loading?: boolean
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive<ProductAddRequest>({
  name: '',
  description: '',
  categoryId: 0,
  brand: '',
  model: '',
  price: 0,
  costPrice: 0,
  stockQuantity: 0,
  lowStockThreshold: 0,
  weight: 0,
  volume: 0,
  images: []
})

// 分类选项
const categoryOptions = ref([
  { label: '电子产品', value: 1 },
  { label: '服装鞋帽', value: 2 },
  { label: '家居用品', value: 3 },
  { label: '食品饮料', value: 4 },
  { label: '图书音像', value: 5 },
  { label: '运动户外', value: 6 },
  { label: '美妆护肤', value: 7 },
  { label: '母婴用品', value: 8 }
])

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 200, message: '商品名称长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入销售价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '销售价格必须大于等于0', trigger: 'blur' }
  ],
  costPrice: [
    { type: 'number', min: 0, message: '成本价格必须大于等于0', trigger: 'blur' }
  ],
  stockQuantity: [
    { type: 'number', min: 0, message: '库存数量必须大于等于0', trigger: 'blur' }
  ],
  lowStockThreshold: [
    { type: 'number', min: 0, message: '低库存阈值必须大于等于0', trigger: 'blur' }
  ],
  weight: [
    { type: 'number', min: 0, message: '重量必须大于等于0', trigger: 'blur' }
  ],
  volume: [
    { type: 'number', min: 0, message: '体积必须大于等于0', trigger: 'blur' }
  ]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证图片
    if (form.images && form.images.length > 0) {
      const hasMainImage = form.images.some(img => img.imageType === 1)
      if (!hasMainImage) {
        ElMessage.warning('请至少设置一张主图')
        return
      }
    }
    
    // 验证价格逻辑
    if (form.costPrice && form.costPrice > form.price) {
      ElMessage.warning('成本价格不能大于销售价格')
      return
    }
    
    // 验证库存逻辑
    if (form.lowStockThreshold && form.lowStockThreshold > form.stockQuantity) {
      ElMessage.warning('低库存阈值不能大于库存数量')
      return
    }
    
    emit('submit', { ...form })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 取消操作
const handleCancel = () => {
  emit('cancel')
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    description: '',
    categoryId: 0,
    brand: '',
    model: '',
    price: 0,
    costPrice: 0,
    stockQuantity: 0,
    lowStockThreshold: 0,
    weight: 0,
    volume: 0,
    images: []
  })
  formRef.value?.clearValidate()
}

// 暴露方法
defineExpose({
  resetForm
})

onMounted(() => {
  // 设置默认值
  form.stockQuantity = 0
  form.lowStockThreshold = 0
  form.weight = 0
  form.volume = 0
})
</script>

<style lang="scss" scoped>
.product-add-form {
  .form-section {
    margin-bottom: 24px;
    
    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 500;
      color: #303133;
      
      .el-icon {
        color: #409eff;
      }
    }
  }
  
  .form-tip {
    margin-left: 8px;
    color: #909399;
    font-size: 14px;
  }
  
  .form-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #ebeef5;
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-card__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}
</style>

